package com.sillyhat.project.core.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;
import javax.servlet.ServletContext;

/**
 * @author wanyuxiang
 * @version 1.0
 * @project MGFaceFramework
 * @create 2017-03-23 18:09
 * @desc
 *  Spring容器初始化完成的监听器
 * <br/><br/>
 * ApplicationListener#ContextRefreshedEvent上下文更新完之后触发事件<br/>
 * 实现servletContextAware接口，会在初始化当前Bean的时候，自动注入servletContext这个实例[Bean]<br/>
 * 这个servletContext Bean它是在ApplicationContext#refresh更新上下文的时候注入进来了<br/>
 **/
@Component("initializedApplicationListener")
public class InitializedApplicationListener implements ApplicationListener<ContextRefreshedEvent>, ServletContextAware {

    private static final Logger logger = LoggerFactory.getLogger(InitializedApplicationListener.class);

    private ServletContext servletContext;

    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        if ((this.servletContext != null)&& (contextRefreshedEvent.getApplicationContext().getParent() == null)) {
            logger.info("************Spring容器[上下文更新完成]之后触发事件************");
            //此处做操作

            //
            logger.info("************[上下文更新完成]的触发事件执行完毕,Spring容器[初始化]完成************");
        }
    }
}
